package com.ruoyi.order.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.order.domain.AppStoreNotifyPayLoadDto;
import com.ruoyi.order.domain.OrderEvaluate;
import com.ruoyi.order.pojo.AppApplePayDTO;
import com.ruoyi.order.pojo.AppMyOrderDTO;
import com.ruoyi.order.pojo.AppOrderVO;
import com.ruoyi.order.pojo.AppProjectDTO;
import com.ruoyi.order.service.AppOrderService;
import com.ruoyi.order.service.IOrderInfoService;

import io.swagger.annotations.Api;

@RestController
@RequestMapping("/api/v1/order")
@Api(tags = "【APP】订单相关接口")
@CrossOrigin
public class AppOrderController {
	
	@Autowired
	private AppOrderService appOrderService;
	@Autowired
	private IOrderInfoService orderInfoService;
	
	/**
	 * 	获取支付订单
	 * @param payType		1=微信 2=支付宝 3=余额支付
	 * @param businessId	业务ID
	 * @param money			金额-安卓自定义充值
	 * @param type			1=充值VIP  6=充值余额
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/getOrder")
	public AjaxResult getOrder(@RequestBody AppOrderVO appOrderVO,HttpServletRequest request) {
		if(null == appOrderVO) {
			return AjaxResult.error("支付无效，请选择支付方式再操作");
		}
		if(1 == appOrderVO.getPayType()) {
			return AjaxResult.error("微信支付维护中暂不支持微信支付");
		}
//		if(2 == appOrderVO.getPayType()) {
//			return AjaxResult.error("支付宝支付维护中暂不支持支付宝支付");
//		}
		if(StringUtils.isEmpty(appOrderVO.getOrderNo())) {
			if (appOrderVO.getPayType() == null || (appOrderVO.getBusinessId() == null && null == appOrderVO.getMoney() && StringUtils.isEmpty(appOrderVO.getDynamicIds())) 
					|| appOrderVO.getType() == null) {
				return AjaxResult.error("支付无效，请选择支付方式再操作");
			}
		}
		if(1 != appOrderVO.getPayType() && 2 != appOrderVO.getPayType() && 3 != appOrderVO.getPayType()) {
			return AjaxResult.error("未知支付方式");
		}
		
		return appOrderService.getOrder(appOrderVO.getPayType(), appOrderVO.getBusinessId(), appOrderVO.getMoney(), appOrderVO.getType(),appOrderVO.getOrderNo(),appOrderVO.getDynamicIds(), 
				appOrderVO.getCouponId(), appOrderVO.getToUserId(), request);
	}
	
	/**
	 * 	我的订单
	 * @param orderStatus	1=待付款 2=待服务 3=进行中 4=已完成
	 * @param pageNo		开始页
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/getOrderList")
	public AjaxResult getOrderList(Integer orderStatus,Integer pageNo,HttpServletRequest request) {
		//Assert.isTrue(false, "数据不存在");
		if(null == orderStatus) orderStatus = 1;
		if(null == pageNo) pageNo = 1;
		return appOrderService.getOrderList(orderStatus,pageNo,request);
	}
	
	/**
	 * 	取消订单
	 * @param order		订单号
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/cancelOrder")
	public AjaxResult cancelOrder(@RequestBody AppMyOrderDTO order,HttpServletRequest request) {
		if(null == order || StringUtils.isEmpty(order.getOrderNo())) {
			return AjaxResult.error("请选择订单");
		}
		return appOrderService.cancelOrder(order.getOrderNo(),request);
	}
	
	/**
	 * 	订单 催单
	 * @param order			订单号
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/reminderOrder")
	public AjaxResult reminderOrder(@RequestBody AppMyOrderDTO order,HttpServletRequest request) {
		if(null == order || StringUtils.isEmpty(order.getOrderNo())) {
			return AjaxResult.error("请选择订单");
		}
		return appOrderService.reminderOrder(order.getOrderNo(),request);
	}
	
	/**
	 * 	订单投诉
	 * @param order
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/orderComplaint")
	public AjaxResult orderComplaint(@RequestBody AppMyOrderDTO order,HttpServletRequest request) {
		if(null == order || StringUtils.isEmpty(order.getContent())) {
			return AjaxResult.error("请输入投诉内容");
		}
		return appOrderService.orderComplaint(order,request);
	}
	
	/**
	 * 	订单评价
	 * @param orderEvaluate
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/orderEvaluate")
	public AjaxResult orderComplaint(@RequestBody OrderEvaluate orderEvaluate,HttpServletRequest request) {
		if(null == orderEvaluate || StringUtils.isEmpty(orderEvaluate.getContent())) {
			return AjaxResult.error("请输入评价内容");
		}
		if(StringUtils.isEmpty(orderEvaluate.getOrderNo())) {
			return AjaxResult.error("请输入订单号");
		}
		return appOrderService.orderEvaluate(orderEvaluate,request);
	}
	
	
	/**
	 * 用于微信回调
	 */
	@RequestMapping(value = "/notifyFromWxpay", method = { RequestMethod.POST, RequestMethod.GET })
	public String notifyFromWxpay(HttpServletRequest httpServletRequest) {
		InputStream is = null;
		String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
		try {
			is = httpServletRequest.getInputStream();
			// 将InputStream转换成String
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			xmlBack = orderInfoService.notifyFromWxpay(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return xmlBack;
	}
	
	/**
	 * 用于支付宝回调
	 */
	@RequestMapping(value = "/notifyFromAlipay", method = { RequestMethod.POST, RequestMethod.GET })
	public String notifyFromAlipay(HttpServletRequest httpServletRequest) {
		System.out.println("进入支付宝回调============");
		Map<String, String> params = new HashMap<>();
		Map<String, String[]> requestParams = httpServletRequest.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8",token);
			params.put(name, valueStr);
		}
		return orderInfoService.notifyFromAlipay(params);
	}
	
	/**
	 * 	提现记录
	 * @param pageNo
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/withdrawalRecord")
	public AjaxResult withdrawalRecord(Integer pageNo,HttpServletRequest request) {
		if(null == pageNo) {
			pageNo = 1;
		}
		return appOrderService.withdrawalRecord(pageNo,request);
	}
	
	/**
	 * 	充值记录
	 * @param pageNo
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/rechargeRecord")
	public AjaxResult rechargeRecord(Integer pageNo,HttpServletRequest request) {
		if(null == pageNo) {
			pageNo = 1;
		}
		return appOrderService.rechargeRecord(pageNo,request);
	}
	
	/**
	 * 	VIP购买记录
	 * @param pageNo
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/vipBuyRecord")
	public AjaxResult vipBuyRecord(Integer pageNo,HttpServletRequest request) {
		if(null == pageNo) {
			pageNo = 1;
		}
		return appOrderService.vipBuyRecord(pageNo,request);
	}
	
	/**
	 * 	购买VIP
	 * @param appOrderVO.businessId  VIP规格ID
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/buyVip")
	public AjaxResult buyVip(@RequestBody AppOrderVO appOrderVO,HttpServletRequest request) {
		if(null == appOrderVO || null == appOrderVO.getBusinessId()) {
			return AjaxResult.error("请选择VIP规格");
		}
		return appOrderService.buyVip( appOrderVO.getBusinessId(), request);
	}
	
	/**
	 * 	咨询项目操作
	 * @param pageNo
	 * @return
	 */
	@PostMapping(value = "/projectOperate")
	public AjaxResult projectOperate(@RequestBody AppProjectDTO project) {
		if(null == project || StringUtils.isEmpty(project.getOrderNo()) || null == project.getType()) {
			return AjaxResult.error("参数异常");
		}
		return appOrderService.projectOperate(project);
	}
	
	/**
	 * 	收益记录
	 * @param pageNo
	 * @return
	 */
	@GetMapping(value = "/getIncomeRecord")
	public AjaxResult getIncomeRecord(Integer pageNo) {
		if(null == pageNo) {
			pageNo = 1;
		}
		return appOrderService.getIncomeRecord(pageNo);
	}
	
	/**
	 * 	消费记录
	 * @param pageNo
	 * @return
	 */
	@GetMapping(value = "/getConsumeRecord")
	public AjaxResult getConsumeRecord(Integer pageNo) {
		if(null == pageNo) {
			pageNo = 1;
		}
		return appOrderService.getConsumeRecord(pageNo);
	}
	
	
	/**
	 * 	苹果支付
	 * @param appApplePayDTO
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/applePay")
	public AjaxResult applePay(@RequestBody AppApplePayDTO appApplePayDTO,HttpServletRequest request) {
		if(null == appApplePayDTO || StringUtils.isEmpty(appApplePayDTO.getTransactionId()) || StringUtils.isEmpty(appApplePayDTO.getPayload())
				|| null == appApplePayDTO.getBusinessId() || null == appApplePayDTO.getType()) {
			return AjaxResult.error("非法访问");
		}
		return orderInfoService.applePay(appApplePayDTO.getPayload(),appApplePayDTO.getTransactionId(), appApplePayDTO.getBusinessId(),appApplePayDTO.getType(),appApplePayDTO.getToUserId(),request);
	}
	
	// 是否可以充值VIP
	@GetMapping(value = "/isRecharge")
	public AjaxResult isRecharge(HttpServletRequest request) {
		return orderInfoService.isRecharge();
	}
	
	
	@PostMapping("/applePayNotify")
    public String appStoreMsgNotify(@RequestBody AppStoreNotifyPayLoadDto appStoreNotifyPayLoadDto) {
		appOrderService.appStoreMsgNotify(appStoreNotifyPayLoadDto);
        return "200";
    }
}